import React from 'react';
import {Steps, Form, Button, Row, Col, Input, Select, Icon, AutoComplete} from 'antd';
import {sex} from '@assets/config/global.js';
import Tools from '@untils/tools.jsx';
import RCModal from '@components/modal/index.jsx';

import Request from '@ajax/index.jsx';
import {APIS_HELP_MANAGE} from '@apis/index.js';

import './scss/help_manage_modal.scss';

const Step = Steps.Step;
const FormItem = Form.Item;
const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;
const _req = new Request();

class HelpManageModal extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            current: 0,
            poorsResult: [],
            stepOneData: {},
            stepOneError: true,

            caderResult: [],
            stepTwoData: {},
            stepTwoError: true,
            stepThreeData: {},
            showFooter: true
        };
        this.setCallback = Tools.setCallback.bind(this);
        this.clearTime = null;
    }

    componentDidMount() {
        let {
            cadreData = null,
            poorData = null,
            showFooter = true,
            currentStep = 0
        } = this.props;
        let stepOneError = !cadreData&&!poorData;
        let stepThreeData = {}
        if (cadreData&&poorData) {
            stepThreeData = {
                ...poorData,
                caderName: cadreData.name,
                project: cadreData.project,
                money: cadreData.money
            };
        }
        (cadreData&&poorData)&&this.setCallback({stepTwoData: cadreData, stepOneData: poorData, stepThreeData, stepOneError, showFooter, current: currentStep})
    }

    // 取消
    onCancel() {
        this.setState({current: 0})
        this.props.form.resetFields();
        this.props.cancelForm();
    }

    // 继续添加
    resetContent() {
        this.setCallback({
            current: 0,
            poorsResult: [],
            stepOneData: {},
            stepOneError: true,
            caderResult: [],
            stepTwoData: {},
            stepTwoError: true,
            stepThreeData: {}

        }, this.props.form.resetFields);
    }

    // 输入帮扶对象
    requestPoors(val) {
        clearInterval(this.clearTime);
        let data = {
            pagination: {
                currentPage: 0,
                pageSize: 0
            },
            searchContent: {
                name: val
            }
        };
        let options = Tools.objectAssign(APIS_HELP_MANAGE.POORLIST, {data, loading: false});
        this.clearTime = setTimeout(() => _req.axios(options).then(data => {
            let poorsResult = data.content || [];
            this.setCallback({poorsResult, stepOneData: {}, stepOneError: true});
        }), 200);
    }

    // 扶贫对象选择一项
    poorsSelect(val) {
        let {poorsResult} = this.state;
        let stepOneData = null;
        poorsResult.map(item => {
            if (item.id  === val - 0)
                stepOneData = item;
            return null;
        });
        this.setCallback({stepOneData}, this.judgestepOne);
    }

    // 验证第一步
    judgestepOne() {
        let {getFieldsValue} = this.props.form;
        let stepOneData = getFieldsValue(['name', 'sex', 'idCard', 'address']);
        let stepOneError = Object.keys(stepOneData).some(item => stepOneData[item] === undefined);
        this.setCallback({stepOneError});
    }

    // 获取帮扶干部
    requestCadre(val) {
        clearInterval(this.clearTime);
        let data = {
            pagination: {
                currentPage: 0,
                pageSize: 0
            },
            searchContent: {
                name: val
            }
        };
        let options = Tools.objectAssign(APIS_HELP_MANAGE.CADRELIST, {data, loading: false});
        this.clearTime = setTimeout(() => _req.axios(options).then(data => {
            let caderResult = data.content || [];
            this.setCallback({caderResult, stepTwoData: {}, stepTwoError: true});
        }), 200);
    }

    // 扶贫干部选择一项
    caderSelect(val) {
        let {caderResult} = this.state;
        let stepTwoData = null;
        caderResult.map(item => {
            if (item.id  === val - 0)
                stepTwoData = item;
            return null;
        });
        this.setCallback({stepTwoData}, this.judgestepTwo);
    }

    // 验证第而步
    judgestepTwo() {
        let {getFieldsValue} = this.props.form;
        let stepTwoData = getFieldsValue(['caderName', 'project', 'money', 'time']);
        let stepTwoError = Object.keys(stepTwoData).some(item => stepTwoData[item] === '');
        this.setCallback({stepTwoError});
    }

    // stepTwoChange
    stepTwoChange() {
        clearInterval(this.clearTime);
        this.clearTime = setTimeout(() => this.judgestepTwo(), 100);
    }

    // 第二部充公
    stepTwoSucess() {
        let formInfo = this.props.form.getFieldsValue();
        let {stepOneData, stepTwoData} = this.state;
        let {cadreData = null, poorData = null} = this.props;
        let data = {
            poorId: formInfo.poorId,
            cadreId: formInfo.cadreId,
            project: formInfo.project,
            money: formInfo.money,
            time: formInfo.time
        };
        let API = {};
        if (cadreData!==null&&poorData!==null) {
            // 编辑
            API = APIS_HELP_MANAGE.EDITHELP;
            // 添加纪录id
            data.id = cadreData.recordId;
        } else {
            // 新增
            API = APIS_HELP_MANAGE.APPEDNHELP
        }
        let options = Tools.objectAssign(API, {data, loading: false});
        _req.axios(options).then(res => {
            let stepThreeData = {...formInfo, name: stepOneData.name, caderName: stepTwoData.name};

            this.setCallback({stepThreeData: stepThreeData, current: 2});
        })
    }

    render() {
        let currentStep = this.props.currentStep;
        let {
            current,
            poorsResult,
            stepOneData,
            stepOneError,
            caderResult,
            stepTwoData,
            stepTwoError,
            stepThreeData,
            showFooter
        } = this.state;

        const {modalVisible = false} = this.props;

        // 扶贫对象选择
        const poorsOption = poorsResult.map(item => (
            <AutoCompleteOption key={item.id}>{item.name}</AutoCompleteOption>
        ));
        // 帮扶对象选择
        const cadersOption = caderResult.map(item => (
            <AutoCompleteOption key={item.id}>{item.name}</AutoCompleteOption>
        ));

        const {getFieldDecorator/*, getFieldsError, getFieldError, isFieldTouched*/} = this.props.form;

        const formItemLayout = {
            colon: false,
            labelCol: {
                span: 8
            },
            wrapperCol: {
                span: 16
            }
        };

        const rules = [{required: true, message: '必填项！'}];

        return (
            <RCModal
                visible={modalVisible}
                width={800}
                showFooter={false}
                onCancel={this.onCancel.bind(this)}
                title="帮扶管理"
            >
                <div className='help-manage-modal'>
                    {
                        currentStep === 2
                            ? null
                            : <Steps current={current} size='small' className='steps'>
                                <Step title="选择帮扶对象"/>
                                <Step title="填写帮扶信息"/>
                                <Step title="完成"/>
                            </Steps>
                    }

                    <Form layout='horizontal'>
                        <FormItem style={{display: 'none'}}>
                            {
                                getFieldDecorator('poorId', {initialValue: stepOneData.id||''})(
                                    <Input disabled={true}/>
                                )
                            }
                        </FormItem>
                        <div className="form-item" style={{height: current === 0 ? '100%' : '0'}}>
                            <div className="cc-area modal-content">
                                <Row>
                                    <Col span={24}>
                                        <FormItem label='扶贫对象姓名' {...formItemLayout}>
                                            {
                                                getFieldDecorator('name', {initialValue: stepOneData.name || '', rules})(
                                                    <AutoComplete
                                                        dataSource={poorsOption}
                                                        onSearch={(val) => this.requestPoors(val)}
                                                        onSelect={(val) => this.poorsSelect(val)}
                                                        placeholder="输入姓名"
                                                    >
                                                        <Input />
                                                    </AutoComplete>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={24}>
                                        <FormItem label='性别' {...formItemLayout}>
                                            {
                                                getFieldDecorator('sex', {initialValue: sex[stepOneData.sex] ? '' : stepOneData.sex})(
                                                    <Select style={{width: '100%'}} disabled={true} placeholder='请选择'>
                                                        {
                                                            Object.keys(sex).map((item, index) => {
                                                                return (
                                                                    <Option value={sex[item].id} key={index}>{sex[item].name}</Option>
                                                                )
                                                            })
                                                        }
                                                    </Select>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>

                                <Row>
                                    <Col span={24}>
                                        <FormItem label='证件号码' {...formItemLayout}>
                                            {
                                                getFieldDecorator('idCard', {initialValue: stepOneData.idCard || ''})(
                                                    <Input placeholder='请输入' disabled={true}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>

                                <Row>
                                    <Col span={24}>
                                        <FormItem label='联系电话' {...formItemLayout}>
                                            {
                                                getFieldDecorator('phone', {initialValue: stepOneData.phone || ''})(
                                                    <Input placeholder='请输入' disabled={true}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>

                                <Row>
                                    <Col span={24}>
                                        <FormItem label='家庭住址' {...formItemLayout}>
                                            {
                                                getFieldDecorator('address', {initialValue: stepOneData.address || ''})(
                                                    <Input placeholder='请输入' disabled={true}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>
                            </div>
                        </div>


                        <div className="form-item" style={{height: current === 1 ? '100%' : '0'}}>
                            <FormItem style={{display: 'none'}}>
                                {
                                    getFieldDecorator('cadreId', {initialValue: stepTwoData.id||''})(
                                        <Input disabled={true}/>
                                    )
                                }
                            </FormItem>
                            <div className="cc-area modal-content">
                                <Row>
                                    <Col span={24}>
                                        <FormItem label='帮扶干部名称' {...formItemLayout}>
                                            {
                                                getFieldDecorator('caderName', {initialValue: stepTwoData.name || '', rules})(
                                                    <AutoComplete
                                                        dataSource={cadersOption}
                                                        onSearch={(val) => this.requestCadre(val)}
                                                        onSelect={(val) => this.caderSelect(val)}
                                                        placeholder="输入姓名"
                                                    >
                                                        <Input />
                                                    </AutoComplete>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={24}>
                                        <FormItem label='帮扶项目名称' {...formItemLayout}>
                                            {
                                                getFieldDecorator('project', {initialValue: stepTwoData.project || '', rules})(
                                                    <Input placeholder='请输入' onChange={() => this.stepTwoChange()}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>

                                <Row>
                                    <Col span={24}>
                                        <FormItem label='帮扶金额' {...formItemLayout}>
                                            {
                                                getFieldDecorator('money', {initialValue: stepTwoData.money || '', rules})(
                                                    <Input placeholder='请输入' onChange={() => this.stepTwoChange()}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>

                                <Row>
                                    <Col span={24}>
                                        <FormItem label='帮扶时间' {...formItemLayout}>
                                            {
                                                getFieldDecorator('time', {initialValue: stepTwoData.time || '', rules})(
                                                    <Input placeholder='请输入' onChange={() => this.stepTwoChange()}/>
                                                )
                                            }
                                        </FormItem>
                                    </Col>
                                </Row>
                            </div>
                        </div>

                        <div className="form-item" style={{height: current === 2 ? '100%' : '0'}}>
                            <div className="cc-area modal-content">
                                <div className="success-flag">
                                    <Icon
                                        type="check-circle"
                                        theme="twoTone"
                                        twoToneColor="#52c41a"
                                        style={{fontSize: 36}}
                                    />
                                    <p className="warning-success">操作成功</p>
                                </div>
                                <Row>
                                    <Col span={8} className='col-each title-name-par'>
                                        <span className="title-name">帮扶对象：</span>
                                    </Col>
                                    <Col span={16} className='col-each'>
                                        <span className="item-val">{stepThreeData.name}</span>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={8} className='col-each title-name-par'>
                                        <span className="title-name">证件号码：</span>
                                    </Col>
                                    <Col span={16} className='col-each'>
                                        <span className="item-val">{stepThreeData.idCard}</span>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={8} className='col-each title-name-par'>
                                        <span className="title-name">家庭住址：</span>
                                    </Col>
                                    <Col span={16} className='col-each'>
                                        <span className="item-val">{stepThreeData.address}</span>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={8} className='col-each title-name-par'>
                                        <span className="title-name">扶贫干部：</span>
                                    </Col>
                                    <Col span={16} className='col-each'>
                                        <span className="item-val">{stepThreeData.caderName}</span>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={8} className='col-each title-name-par'>
                                        <span className="title-name">扶贫项目：</span>
                                    </Col>
                                    <Col span={16} className='col-each'>
                                        <span className="item-val">{stepThreeData.project}</span>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={8} className='col-each title-name-par'>
                                        <span className="title-name">扶贫金额：</span>
                                    </Col>
                                    <Col span={16} className='col-each'>
                                        <span className="item-val">{stepThreeData.money}</span>
                                    </Col>
                                </Row>
                            </div>
                        </div>
                    </Form>
                    <div className="line-btns">
                        {
                            (showFooter&&current === 0)
                                ?<Button
                                    type="primary"
                                    disabled={stepOneError}
                                    onClick={() => this.setCallback({current: 1}, this.judgestepTwo)}
                                >下一步</Button>
                                : null
                        }
                        {
                            (showFooter && current === 1)
                            ? <Button type="primary" disabled={stepTwoError}
                                      onClick={() => this.stepTwoSucess()}>下一步</Button>
                            : null
                        }
                        {
                            showFooter&& current === 2
                                ? <div className="btns-part">
                                    <Button
                                        type="primary"
                                        style={{marginRight: '20px'}}
                                        onClick={this.resetContent.bind(this)}
                                    >继续添加</Button>
                                    <Button onClick={this.onCancel.bind(this)}>返回</Button>
                                </div>
                                : null
                        }
                    </div>
                </div>
            </RCModal>
        )
    }
}


HelpManageModal = Form.create({})(HelpManageModal);

export default HelpManageModal;